﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AntUnion.FrameWork.Model.Models;
using Microsoft.AspNetCore.Hosting;
using Util.Extension;
using AntUnion.FrameWork.Web.Extend;
using AntUnion.FrameWork.Util;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class CodesController : BaseController
    {
        private readonly mtContext _context;
        private readonly IWebHostEnvironment hostingEnv;
        public CodesController(mtContext context, IWebHostEnvironment env) : base(context, env)
        {
            hostingEnv = env;
            _context = context;
        }

        #region 子项列表
        public IActionResult Index(string type)
        {
            ViewBag.type = type;
            return View();
        }

        /// <summary>
        /// 获取子项列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit, string type)
        {
            ListResult res = new ListResult();
            try
            {
                var data = from n in _context.TbCodes.AsNoTracking().Where(k => k.CoType == type && k.Status==0)
                           join c in _context.TbCodetypes.AsNoTracking()
                           on n.CoType equals c.CtCode
                           select new
                           {
                               id = n.CoId,
                               type = c.CtCode,
                               typeName = c.CtName,
                               names = n.CoName,
                               levelSort = n.CoCode,
                               code = n.CoCode,
                               remark = n.CoRemark,
                               creator = n.CoCreate,
                               createDate = n.CoCreateTime,
                               sort = n.CoSort
                           };
                res.Code = 0;
                res.Count = _context.TbCodes.Where(k => k.CoType == type).Count();
                if (page == 0 && limit == 0)
                {
                    res.Data = await data.OrderBy(k => k.sort).ToListAsync();
                }
                else
                {
                    res.Data = await data.OrderBy(k => k.sort).Skip((page - 1) * limit).Take(limit).ToListAsync();
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 添加子项
        public IActionResult Create(string type)
        {
            TbCodetype TbCodetype = _context.TbCodetypes.Where(k => k.CtCode == type).FirstOrDefault();
            TbCode model = new TbCode();
            if (TbCodetype != null)
            {
                if (_context.TbCodes.Any(k => k.CoType == type))
                {
                    model.CoSort = _context.TbCodes.Where(k => k.CoType == type).Max(k => k.CoSort) + 1;
                }
                else
                {
                    model.CoSort = 1;
                }
                model.CoType = type;
                ViewBag.TypeName = TbCodetype.CtName;
            }
            else
            {
                ViewBag.TypeName = "";
            }
            return View(model);
        }

        /// <summary>
        /// 添加子项
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Create(TbCode model)
        {
            Result res = new Result();
            try
            {
                bool isExists = false;
                if (model.CoType == "rebateLevel")
                {
                    isExists = TbCodeExists(model.CoCode, model.CoType);
                }
                else
                {
                    isExists = TbNameExists(model.CoName, model.CoType);
                }
                if (!isExists)
                {
                    model.CoCreate = User.LoginName;
                    model.CoCreateTime = DateTimeUtil.Now;
                    _context.Add(model);
                    res.Code = 0;
                    res.Data = await _context.SaveChangesAsync();
                    RemoveCache();
                }
                else
                {
                    res.Code = 1;
                    res.Data = "addTermExist";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = "submitFail";
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑子项信息
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            TbCode TbCode = await _context.TbCodes.FindAsync(id);
            if (TbCode == null)
            {
                return NotFound();
            }
            TbCodetype TbCodetype = _context.TbCodetypes.Where(k => k.CtCode == TbCode.CoType).FirstOrDefault();
            if (TbCodetype != null)
            {
                ViewBag.TypeName = TbCodetype.CtName;
            }
            else
            {
                ViewBag.TypeName = "";
            }
            return View(TbCode);
        }
        /// <summary>
        /// 编辑子项信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Edit(TbCode item)
        {
            Result res = new Result();
            try
            {
                bool isExists = false;
                if (item.CoType == "rebateLevel")
                {
                    isExists = TbCodeExists(item.CoCode, item.CoType, item.CoId);
                }
                else
                {
                    isExists = TbNameExists(item.CoName, item.CoType, item.CoId);
                }
                if (!isExists)
                {
                    TbCode model = await _context.TbCodes.FindAsync(item.CoId);
                    if (model != null)
                    {
                        model.CoName = item.CoName;
                        model.CoCode = item.CoCode;
                        model.CoSort = item.CoSort;
                        model.CoRemark = item.CoRemark;
                        model.CoNameEn = item.CoNameEn;
                        model.CoUpdate = User.LoginName;
                        model.CoUpdateTime = DateTimeUtil.Now;
                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                        RemoveCache();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Data = "editTermNotExist";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Data = "addTermExist";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = "submitFail";
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除子项
        /// <summary>
        /// 删除单个子项
        /// </summary>
        /// <param name="id">子项ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("Delete")]
        public async Task<JsonResult> Delete(int id)
        {
            Result res = new Result();
            try
            {
                TbCode TbCode = await _context.TbCodes.FindAsync(id);
                _context.TbCodes.Remove(TbCode);
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                RemoveCache();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids">要删除的子项ID；多个用“,”分开</param>
        /// <returns></returns>
        [HttpPost, ActionName("DeleteItems")]
        public async Task<IActionResult> DeleteItems(string ids)
        {
            Result res = new Result();
            try
            {
                List<int> list = new List<int>();
                string[] idList = ids.Split(',');
                foreach (string id in idList)
                {
                    list.Add(id.ToInt());
                }
                List<TbCode> itemList = await _context.TbCodes.Where(k => list.Contains(k.CoId)).ToListAsync();
                foreach (TbCode model in itemList)
                {
                    _context.TbCodes.Remove(model);
                }
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                RemoveCache();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="Name">子项名称称</param>
        /// <param name="id">排除ID</param>
        /// <returns></returns>
        private bool TbCodeExists(int code, string type, int id = 0)
        {
            if (id == 0)
                return _context.TbCodes.Any(e => e.CoCode == code && e.CoType == type);
            else
                return _context.TbCodes.Any(e => e.CoId != id && e.CoCode == code && e.CoType == type);
        }

        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="Name">子项名称称</param>
        /// <param name="id">排除ID</param>
        /// <returns></returns>
        private bool TbNameExists(string Name, string type, int id = 0)
        {
            if (id == 0)
                return _context.TbCodes.Any(e => e.CoName == Name && e.CoType == type);
            else
                return _context.TbCodes.Any(e => e.CoId != id && e.CoName == Name && e.CoType == type);
        }
        #endregion

        #region 清除缓存
        public void RemoveCache()
        {
            //DefaultCache.Remove(BaseData.Cache.Problem);
            //DefaultCache.Remove(BaseData.Cache.International);
            //DefaultCache.Remove(BaseData.Cache.RechargeAmount);
        }
        #endregion
    }
}
